package cn.iocoder.yudao.module.system.service.a_quest;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import cn.iocoder.yudao.module.system.controller.admin.a_quest.vo.*;
import cn.iocoder.yudao.module.system.controller.admin.permission.vo.menu.MenuListReqVO;
import cn.iocoder.yudao.module.system.convert.a_quest.QuestConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.a_quest.QuestDO;
import cn.iocoder.yudao.module.system.dal.mysql.a_quest.QuestMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.ibatis.jdbc.Null;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants._NOT_EXISTS;

/**
 * 待办 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class QuestServiceImpl implements QuestService {

    @Resource
    private QuestMapper questMapper;

    @Override
    public Integer create(QuestCreateReqVO createReqVO) {
        // 插入
        createReqVO.setTransactor(WebFrameworkUtils.getLoginUserId().toString());
        createReqVO.setStatus(0);
        QuestDO questDO = QuestConvert.INSTANCE.convert(createReqVO);
        questMapper.insert(questDO);
        // 返回
        return questDO.getId();
    }

    @Override
    public void update(QuestUpdateReqVO updateReqVO) {
        // 校验存在
        validateExists(updateReqVO.getId());
        // 更新
        QuestDO updateObj = QuestConvert.INSTANCE.convert(updateReqVO);
        questMapper.updateById(updateObj);
    }

    @Override
    public void delete(Integer id) {
        // 校验存在
        validateExists(id);
        // 删除
        questMapper.deleteById(id);
    }

    private void validateExists(Integer id) {
        if (questMapper.selectById(id) == null) {
            throw exception(_NOT_EXISTS);
        }
    }

    @Override
    public QuestDO get(Integer id) {
        return questMapper.selectById(id);
    }

    @Override
    public List<QuestDO> getList(Collection<Integer> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return questMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<QuestDO> selectPageSuccess(QuestPageReqVO pageReqVO) {
        return questMapper.selectPageSuccess(pageReqVO);
    }

    @Override
    public PageResult<QuestDO> getPage(QuestPageReqVO pageReqVO) {
        return questMapper.selectPage(pageReqVO);
    }

    @Override
    public List<QuestDO> getList(QuestExportReqVO exportReqVO) {
        return questMapper.selectList(exportReqVO);
    }

    @Override
    public List<QuestDO> getEndTimeQuest() {
        return questMapper.getEndTimeQuest(WebFrameworkUtils.getLoginUserId().toString());
    }

    @Override
    public List<QuestDO> getMonthQuest() {
        return questMapper.getMonthQuest(WebFrameworkUtils.getLoginUserId().toString());
    }

    @Override
    public Map<String, Integer> countQuest() {
        Map<String, Integer> map = new HashMap<>();
        map.put("questCount", questMapper.countQuest(WebFrameworkUtils.getLoginUserId().toString()));
        map.put("endTimeCount", questMapper.countEndTimeQuest(WebFrameworkUtils.getLoginUserId().toString()));
        return map;
    }

    @Override
    public Integer createByERP(String questName, String erpId) {
        // 插入
        QuestCreateReqVO createReqVO = new QuestCreateReqVO();
        createReqVO.setQuestname(questName);
        createReqVO.setErpid(erpId);
        createReqVO.setTransactor(WebFrameworkUtils.getLoginUserId().toString());
        createReqVO.setQuesttype(0);
        createReqVO.setPid(0);
        createReqVO.setStatus(null);
        QuestDO questDO = QuestConvert.INSTANCE.convert(createReqVO);
        questMapper.insert(questDO);
        // 返回
        return questDO.getId();
    }


    @Override
    public PageResult<ResultTreeVO> getQuestList(QuestListReqVO reqVO) {
        PageResult<ResultTreeVO> listResult = new PageResult<>();
        PageResult<QuestDO> list = questMapper.selectQueryList(reqVO);
        listResult = convertToResultTree(list);
        listResult.getList().forEach(item -> {
            //添加子节点
            if (isExitChildren(item.getId())) {
                reqVO.setPid(item.getId());
                List<QuestDO> children = getQuestChildrenList(reqVO);
                item.setChildren(children);
            }
        });
        return listResult;

    }

    @Override
    public List<QuestDO> getQuestChildrenList(QuestListReqVO reqVO) {
        return questMapper.selectQuestChildrenList(reqVO);
    }

    @Override
    public Boolean isExitChildren(Integer pid) {
        Integer exitChildren = questMapper.isExitChildren(pid);
        if (exitChildren > 0) {
            return true;
        }
        return false;

    }

    @Override
    public PageResult<ResultTreeVO> getErpQuestList(QuestListReqVO reqVO) {
        PageResult<ResultTreeVO> listResult = new PageResult<>();
        PageResult<QuestDO> list = questMapper.selectErpQueryList(reqVO);
        if(list.getTotal() == 0){
            //没有数据则创建数据
            createByERP(reqVO.getQuestname(),reqVO.getErpid());
            list = questMapper.selectErpQueryList(reqVO);
        }
        listResult = convertToResultTree(list);
        listResult.getList().forEach(item -> {
            //添加子节点
            if (isExitChildren(item.getId())) {
                reqVO.setPid(item.getId());
                reqVO.setErpid(null);
                List<QuestDO> children = questMapper.selectErpQuestChildrenList(reqVO);
                item.setChildren(children);
            }
        });
        return listResult;
    }

    public PageResult<ResultTreeVO> convertToResultTree(PageResult<QuestDO> list){
        PageResult<ResultTreeVO> listResult = new PageResult<>();
        List<ResultTreeVO> listTree = new ArrayList<>();
        for(QuestDO questDO:list.getList()){
            ResultTreeVO result = new ResultTreeVO();
            result.setId(questDO.getId());
            result.setPid(questDO.getPid());
            result.setCreatetime(questDO.getCreatetime());
            result.setQuestname(questDO.getQuestname());
            result.setQuesttype(questDO.getQuesttype());
            result.setEndtime(questDO.getEndtime());
            result.setErpid(questDO.getErpid());
            result.setRelevanceid(questDO.getRelevanceid());
            result.setRemark(questDO.getRemark());
            result.setStatus(questDO.getStatus());
            result.setTransactor(questDO.getTransactor());
            listTree.add(result);
        }
            listResult.setList(listTree);
            listResult.setTotal(list.getTotal());
        return listResult;
    }


}
